<?php
namespace app\controller;

use support\Request;
use EasyWeChat\MiniApp\Application;
use Tinywan\Jwt\JwtToken;
use support\Db;

class UserController
{
    public function login(Request $request)
    {
        try {
            $code = $request->post('code');
            if (empty($code)) {
                return json([
                    'code' => 400,
                    'msg' => '缺少code参数'
                ]);
            }

            // 初始化小程序
            $config = config('wechat.mini_program');
            $app = new Application($config);
            
            // 获取openid和session_key
            $response = $app->getUtils()->codeToSession($code);
            
            if (isset($response['errcode'])) {
                return json([
                    'code' => 400,
                    'msg' => $response['errmsg']
                ]);
            }

            $openid = $response['openid'];
            
            // 查找或创建用户
            $user = Db::table('wa_users')->where('openid', $openid)->first();
            if (!$user) {
                Db::beginTransaction();
                try {
                    // 创建新用户
                    $userId = Db::table('wa_users')->insertGetId([
                        'openid' => $openid,
                        'nickname' => '微信用户',
                        'created_at' => date('Y-m-d H:i:s')
                    ]);

                    // 创建默认账本
                    $bookId = Db::table('account_books')->insertGetId([
                        'user_id' => $userId,
                        'name' => '默认账本',
                        'description' => '我的第一个账本',
                        'created_at' => date('Y-m-d H:i:s')
                    ]);

                    // 添加用户为账本管理员
                    Db::table('account_book_users')->insert([
                        'book_id' => $bookId,
                        'user_id' => $userId,
                        'role' => 1,
                        'created_at' => date('Y-m-d H:i:s')
                    ]);

                    // 设置为默认账本
                    Db::table('wa_users')
                        ->where('id', $userId)
                        ->update([
                            'default_book_id' => $bookId,
                            'updated_at' => date('Y-m-d H:i:s')
                        ]);

                    // 创建默认分类
                    $defaultCategories = [
                        // 支出分类
                        [
                            'name' => '饮食',
                            'color' => '#FF9800',
                            'type' => 1,
                            'sort' => 0
                        ],
                        [
                            'name' => '服饰',
                            'color' => '#E91E63',
                            'type' => 1,
                            'sort' => 1
                        ],
                        [
                            'name' => '出行',
                            'color' => '#2196F3',
                            'type' => 1,
                            'sort' => 2
                        ],
                        [
                            'name' => '住房',
                            'color' => '#4CAF50',
                            'type' => 1,
                            'sort' => 3
                        ],
                        // 收入分类
                        [
                            'name' => '工资',
                            'color' => '#009688',
                            'type' => 2,
                            'sort' => 0
                        ],
                        [
                            'name' => '副业',
                            'color' => '#673AB7',
                            'type' => 2,
                            'sort' => 1
                        ]
                    ];

                    foreach ($defaultCategories as $category) {
                        Db::table('categories')->insert([
                            'book_id' => $bookId,
                            'name' => $category['name'],
                            'type' => $category['type'], // 1支出 2收入
                            'color' => $category['color'],
                            'sort' => $category['sort'],
                            'created_at' => date('Y-m-d H:i:s')
                        ]);
                    }

                    Db::commit();
                    $user = Db::table('wa_users')->find($userId);
                } catch (\Exception $e) {
                    Db::rollBack();
                    throw $e;
                }
            }

            // 生成token
            $token = JwtToken::generateToken([
                'id' => $user->id,
                'openid' => $user->openid
            ]);

            // 获取用户信息（包含默认账本）
            $userInfo = Db::table('wa_users as u')
                ->leftJoin('account_books as b', 'u.default_book_id', '=', 'b.id')
                ->where('u.id', $user->id)
                ->select([
                    'u.id',
                    'u.nickname',
                    'u.avatar',
                    'u.default_book_id',
                    'b.name as default_book_name',
                    'b.description as default_book_description'
                ])
                ->first();

            return json([
                'code' => 0,
                'msg' => '登录成功',
                'data' => [
                    'token' => $token,
                    'user_info' => $userInfo
                ]
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    // 更新用户信息
    public function updateUserInfo(Request $request)
    {
        try {
            $nickname = $request->post('nickname');

            Db::table('wa_users')->where('id', $request->uid)->update([
                'nickname' => $nickname,
                'updated_at' => date('Y-m-d H:i:s')
            ]);

            return json([
                'code' => 0,
                'msg' => '更新成功'
            ]);

        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 设置默认账本
     */
    public function setDefaultBook(Request $request)
    {
        try {
            $bookId = $request->post('book_id');
            
            if (empty($bookId)) {
                return json([
                    'code' => 400,
                    'msg' => '参数错误'
                ]);
            }

            // 验证是否是账本成员
            $isMember = Db::table('account_book_users')
                ->where('book_id', $bookId)
                ->where('user_id', $request->uid)
                ->where('status', 1)
                ->exists();

            if (!$isMember) {
                return json([
                    'code' => 403,
                    'msg' => '您不是该账本成员'
                ]);
            }

            // 更新默认账本
            Db::table('wa_users')
                ->where('id', $request->uid)
                ->update([
                    'default_book_id' => $bookId,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);

            return json([
                'code' => 0,
                'msg' => '设置成功'
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取用户信息（包含默认账本）
     */
    public function info(Request $request)
    {
        try {
            $user = Db::table('wa_users as u')
                ->leftJoin('account_books as b', 'u.default_book_id', '=', 'b.id')
                ->where('u.id', $request->uid)
                ->select([
                    'u.id',
                    'u.nickname',
                    'u.avatar',
                    'u.default_book_id',
                    'b.name as default_book_name',
                    'b.description as default_book_description'
                ])
                ->first();

            if (!$user) {
                return json([
                    'code' => 404,
                    'msg' => '用户不存在'
                ]);
            }

            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $user
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => $e->getMessage()
            ]);
        }
    }
} 